# coding=utf-8

from application import app, redis
from common.libs.JsonLibs import bytes_to_obj
from app.model.mysql.game import Game as GameMysql
from app.model.redis.game import Game as GameRedis
from app.json.mysql.game import Game as GameJson


def get_one(game_id):
    redis_game_one = redis.get(GameRedis.game_one.key % game_id)
    if redis_game_one:
        mysql_game_one = None
    else :
        mysql_game_one = GameMysql.query.filter(GameMysql.id == game_id, GameMysql.is_delete == 0).first()
    if mysql_game_one:
        setInRedis(mysql_game_one)
        game_json = GameJson(mysql_game_one).getJson()
    else :
        game_json = bytes_to_obj(redis_game_one)
    return game_json


def get_list():
    redis_game_set = redis.smembers(GameRedis.game_set.key)
    redis_game_list = list(redis_game_set)
    redis_game_list = redis_game_list if redis_game_list else []
    result_list = []
    if not redis_game_list:
        mysql_game_list = GameMysql.query.filter(GameMysql.is_delete == 0).all()
        for mysql_game_one in mysql_game_list:
            setInRedis(mysql_game_one)
            game_one_json = GameJson(mysql_game_one).getJson()
            result_list.append(game_one_json)
        return result_list
    else:
        for game_id in redis_game_list:
            game_one_json = get_one(game_id.decode("utf-8"))
            result_list.append(game_one_json)
        return result_list


def setInRedis(mysql_game_one):
    redis.sadd(GameRedis.game_set.key, mysql_game_one.id)
    redis.set(GameRedis.game_one.key % mysql_game_one.id, GameJson(mysql_game_one).getJsonToRedis())
